<template>
  <div class="wrap">
    <div class="article-detail-title">{{ articleDetail.title }}</div>
    <div v-if="pageTitle!=='话术'" class="article-detail-box">
      <div class="article-detail-authorName">作者：{{ articleDetail.authorName }}</div>
      <div class="article-detail-publishTime">{{ articleDetail.publishTime }}</div>
    </div>
    <div class="article-detail-content">
      <u-parse :content="articleDetail.content" />
    </div>
    <div class="foot">
      <div class="foot-btn">
        <ICON name="icon-reading" size="50" style="margin-right: 20rpx;" />
        <div>阅读</div>
        <div>{{ articleDetail.totalReadingCount }}</div>
      </div>
      <div :class="{ 'foot-btn-act': isLike }" class="foot-btn" @tap.stop="likeFn">
        <ICON v-if="isLike" name="icon-like-act" size="40" style="margin-right: 20rpx;" />
        <ICON v-else name="icon-like" size="40" style="margin-right: 20rpx;" />
        <div>赞</div>
        <div>{{ articleDetail.totalLikingCount }}</div>
      </div>
    </div>
    <div :style="{paddingBottom: `${storeState.bottomSafeDis}rpx`}" class="suction_bottom_btn">
      <template v-if="!isShareEnter">
        <button v-if="pageTitle ==='话术'" class="btn_solid" style="margin-right: 38rpx" @tap="copyToClipboard({content: articleDetail.content})">复制</button>
        <button v-else class="btn_solid" style="margin-right: 38rpx" @tap="showData = true">查看数据</button>
        <button class="btn_primary" open-type="share" @tap="shareFn">分享</button>
      </template>
      <template v-else>
        <button class="btn_solid" style="margin-right: 38rpx" @tap="showConsult = true">问题咨询</button>
        <button class="btn_primary" @tap="goTel(consultFormData.transferMobile)">拨打电话</button>
      </template>
    </div>
    <!--  数据汇总  -->
    <u-popup :show="showData" closeable overlay-opacity="0.45" round="12" safe-area-inset-bottom @close="showData = false">
      <div class="popup_box">
        <div class="popup_title">数据汇总</div>
        <div class="popup_body data flex_sb_cen">
          <div v-for="(item, index) in dataConfig" :key="index" class="data_item" @tap="jumpToPageFn(item)">
            <div :style="{color: item.title === '表单' ? '#FF8002' : '' }" class="data_num">{{ item.num }}</div>
            <div class="data_name">{{ item.title }}</div>
          </div>
        </div>
        <div class="flex_cen_cen">
          <div class="btn_solid" style="width: 90%;" @tap="showData = false">关闭</div>
        </div>
      </div>
    </u-popup>
    <!--  问题咨询  -->
    <u-popup :show="showConsult" closeable overlay-opacity="0.45" round="12" safe-area-inset-bottom @close="showConsult = false">
      <div class="popup_box">
        <div class="popup_title">问题咨询</div>
        <div class="popup_body">
          <div class="popup_name">姓名</div>
          <up-input
            v-model="consultFormData.name"
            :custom-style="{background: '#F5F6F7'}"
            border="surround"
            placeholder="信息已加密，请放心填写"
          />
          <div class="popup_name">电话号码</div>
          <up-input
            v-model="consultFormData.mobile"
            :custom-style="{background: '#F5F6F7'}"
            border="surround"
            maxlength="11"
            placeholder="信息已加密，请放心填写"
            type="number"
          />
          <div class="popup_name">想要咨询的问题</div>
          <u--textarea
            v-model="consultFormData.question"
            :custom-style="{background: '#F5F6F7'}"
            height="314rpx"
            placeholder="信息已加密，请放心填写"
          />
          <button :disabled="!isDisabled" class="btn_primary" style="width: 100%;margin-top: 60rpx;" @tap="commitFn">提交</button>
        </div>
      </div>
    </u-popup>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed } from 'vue'
import {
  checkPhoneFn,
  copyToClipboard,
  obj_oto_query,
  onLoad,
  onShareAppMessage,
  onShareTimeline,
  Router,
  storeState,
} from '@U/common'
import { Msg, MsgLoading, PMsgLoadingClean } from '@C/Msg'
import { getToken } from '@U/Auth'
import ICON from '@C/Icon.vue'
import dayjs from 'dayjs'
import goTel from '@U/goTel'
import {
  getMaterialDetails,
  getMaterialDetailsCommon,
  addReadingCount,
  addLikingCount,
  decreaseLikingCount,
  commitMaterialForm,
  addShareCount,
} from './request'
import type { IObj } from '@/interface'

const isDisabled = computed(() => consultFormData.name && consultFormData.mobile && consultFormData.question)
const dataConfig = [
  {
    title: '浏览量',
    key: 'totalReadingCount',
    num: 0,
  },
  {
    title: '分享数量',
    key: 'totalTransferringCount',
    num: 0,
  },
  {
    title: '点赞数',
    key: 'totalLikingCount',
    num: 0,
  },
  {
    title: '表单',
    key: 'formCount',
    num: 0,
  },
]
const id = ref('')
const title = ref('资料详情')
const isShareEnter = ref(false)
const showData = ref(false)
const showConsult = ref(false)
const materialId = ref('')
const consultFormData = reactive({
  name: '',
  mobile: '',
  question: '',
  materialId: '',
  transferAccountId: '',
  transferIsChannelAgent: true,
  transferMobile: '',
})
const pageTitle = ref('')
onLoad(async (options: any) => {
  pageTitle.value = options.pageTitle
  // 判断是否通过分享链接进入该页面
  if (uni.getLaunchOptionsSync().scene === 1007) {
    isShareEnter.value = true
    consultFormData.materialId = options.materialId
    consultFormData.transferIsChannelAgent = options.transferIsChannelAgent
    consultFormData.transferAccountId = options.transferAccountId
    consultFormData.transferMobile = options.transferMobile
  }
  // 分享给朋友
  onShareAppMessage(() => {
    const articleDetailNew = JSON.parse(JSON.stringify(articleDetail))
    articleDetailNew.content = ''
    return ({
      path: `/pages/Article/ArticleInfo?${obj_oto_query(articleDetailNew)}`,
      title: articleDetail.title,
      imageUrl: options.cover || `${import.meta.env.VITE_SHOUDAO_OSS_URL}/share_artice.png`,
    })
  })
  await uni.setNavigationBarTitle({
    title: `${options.pageTitle }详情`,
  })
  const params = Router.route().params
  if (params?.id) {
    id.value = params?.id
  } else {
    id.value = (obj_oto_query(params?.redirectParams) as IObj)?.id
  }
  if (params?.title) {
    title.value = params.title
  }
  // if (getToken()) {
  //   await uni.setNavigationBarTitle({
  //     title: `${options.title }详情`,
  //   })
  //   // await getLike()
  //   // storeCommit('redirectPath', '')
  //   // storeCommit('redirectParams', {})
  // }
  materialId.value = options.materialId
  await MsgLoading()
  // 增加阅读数
  await addReadingCount({ materialId: options.materialId }).finally(() => {})
  await getObtainArticleDetails()
})

const shareFn = () => {
  addShareCount({ materialId: materialId.value })
}
// onShow(() => {
//   // #ifdef MP
//   // 分享给朋友
//   onShareAppMessage(() => ({
//     path: `/pages/Article/ArticleInfo?${obj_oto_query(shareState.value)}`,
//     title: title.value,
//     imageUrl: `${import.meta.env.VITE_SHOUDAO_OSS_URL}/share_artice.png`,
//   }))
//   // 分享到朋友圈
//   onShareTimeline(() => ({
//     title: title.value,
//     imageUrl: `${import.meta.env.VITE_SHOUDAO_OSS_URL}/share_artice.png`,
//     query: obj_oto_query(shareState.value) as string,
//   }))
//   // #endif
// })

const articleDetail = reactive(<IObj>{
  title: '', // 标题
  authorName: '', // 作者
  publishTime: '', // 发布时间
  content: '', // 内容
  abstract: '',
  totalReadingCount: 0,
  totalLikingCount: 0,
  like: false,
  transferMobile: '',
})

// 获取素材详情
async function getObtainArticleDetails() {
  let api: any
  getToken() ? api = getMaterialDetails : api = getMaterialDetailsCommon
  const res = await api({ materialId: materialId.value }).finally(() => {})
  if (res?.code === 200) {
    PMsgLoadingClean()
    res.data.publishTime = dayjs(res.data?.publishTime).format('YYYY-MM-DD HH:mm')
    for (const key in res.data) {
      articleDetail[key] = res.data[key]
    }
    // 富文本预览标签样式转换
    let text = ''
    text = res.data.content.replace(/<video/gi, '<video style="width: 100%;height:auto" ')
    // text = text.replace(/color="/gi, 'style="color: ')
    // text = text.replace(/style=""/gi, '')
    articleDetail.content = text
    // 给数据汇总弹框赋值
    dataConfig.forEach(item => {
      const findItem = Object.keys(res.data).find(item1 => item1 === item.key)
      item.num = res.data[findItem]
    })
    articleDetail.pageTitle = pageTitle.value
  }
}

const jumpToPageFn = (item: object) => {
  if (item.title !== '表单') return
  if (item.num === 0) return
  Router.push('gl_market_form', { materialId: materialId.value })
}

// 点赞
const isLike = ref(false)
const likeFn = async () => {
  isLike.value = !isLike.value
  if (isLike.value) {
    await addLikingCount({ materialId: materialId.value }).finally(() => {})
    articleDetail.totalLikingCount += 1
  } else {
    await decreaseLikingCount({ materialId: materialId.value }).finally(() => {})
    articleDetail.totalLikingCount -= 1
  }
  // 更新数据汇总中的点赞数
  await getObtainArticleDetails()
}
// 提交素材报表
const commitFn = async () => {
  if (!checkPhoneFn(consultFormData.mobile)) return Msg({ msg: '手机号格式不正确' })
  await MsgLoading()
  await commitMaterialForm(consultFormData).finally(() => PMsgLoadingClean())
  Msg({ msg: '提交成功' })
  showConsult.value = false
}
</script>

<style lang="less">
page {
  background-color: #f2f2f7;
  padding-top: 2rpx;
  box-sizing: border-box;
}
</style>
<style lang="less" scoped>
.wrap {
  background-color: #FFFFFF;
  padding: 24rpx;
  .article-detail-title{
    font-size: 44rpx;
    color:#000000d9;
  }
  .article-detail-box{
    display: flex;
    align-items: center;
    color: #00000040;
    margin: 30rpx 0;
    .article-detail-authorName{
      margin-right: 30rpx;
    }
  }
  .article-detail-content {
    flex: 1 1;
    font-size: 16px;
    overflow-x: hidden;
  }
  .foot{
    height: 140rpx;
    display: flex;
    align-items: center;
    background: #FFFFFF;
    margin-bottom: 120rpx;
    .foot-btn{
      height: 140rpx;
      color: #bfbfbf;
      display: flex;
      align-items: center;
      font-size: 30rpx;
      margin:0 30rpx;
    }
    .foot-btn-act {
      color: #1890ff;
    }
  }
  .popup_box {
    .data {
      margin: 60rpx 0;
      .data_item {
        width: 150rpx;
        text-align: center;
        .data_num {
          font-size: 48rpx;
          font-weight: 500;
          color: rgba(0,0,0,0.65);
          line-height: 66rpx;
        }
        .data_name {
          font-size: 28rpx;
          font-weight: 400;
          color: rgba(0,0,0,0.45);
          line-height: 40rpx;
        }
      }
    }
  }
}
</style>
